#include "Config.h"
#include "Common/TimeUtil.h"
#include "Common/MemStream.h"
#include "LogicWorker.h"
#include "Server.h"
#include "PlayerManager.h"
#include "ServerClientManager.h"

LogicWorker::LogicWorker(UInt8 worker_)
: WorkerRunner<LogicMsgHandler>(500), _tid(worker_)
{
	_pm = new(std::nothrow) PlayerManager();
	_scm = new(std::nothrow) ServerClientManager();
}

LogicWorker::~LogicWorker()
{

}

bool LogicWorker::init()
{
	AddTimer(1 * 1000, Game_Update, this);
	AddTimer(10 * 1000, Server_Update, this);
	AddTimer(120 * 1000, Game_Statistics, this);
	return true;
}

void LogicWorker::Game_Update(LogicWorker * lw)
{
	PM()->update(TimeUtil::Now());
}

void LogicWorker::Server_Update(LogicWorker * lw)
{
	SCM()->update(TimeUtil::Now());
}

void LogicWorker::Game_Statistics(LogicWorker * lw)
{
	UInt32 onlineCount = 0;
	UInt32 roomCount = 0;
	SCM()->getOnlineCount(onlineCount, roomCount);
	onlineCount += PM()->getOnlineCount();
	//
	MemStream ms;
	ms << onlineCount;
	ms << roomCount;
	MsgHdr hdr(ms.size(), 0x220, Thread_DB);
	MSGPOOL().pushMsg(hdr, ms.body());
}

bool LogicWorker::postInit()
{
	init();
	return true;
}

void LogicWorker::unInit()
{
	SAFE_DELETE(_pm);
}

std::string LogicWorker::getLogName()
{
	std::string logPath = "log/";
	logPath.append(SERVER_NAME);
	logPath.append("/");
	std::string logDir = SERVER().getFilePath(logPath);
	return logDir;
}